package com.android.support.lib.universal.load;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.android.support.lib.universal.util.Utilstr;

/**
 * 上传文件
 * 使用说明：
 * 	final Map<String, String> reqHeader = new HashMap<String, String>();//服务器参数，需要服务器支持
	reqHeader.put("filename", file.getName());// 图片文件名
	reqHeader.put("folder", "user");// 图片文件夹
	final File file = new File(filePath);// 文件，filePath文件完整路径，包括后缀名
	// 文件上传，返回文件上传后，服务器URL地址
	final String uploadFile = uploadPicture.uploadFile(file, url, reqHeader);//url为服务器上传url,需要服务器支持
 * @author 彭治铭
 *uploadFile
 */
public class UploadPicture {
	@SuppressWarnings("rawtypes")
	public String uploadFile(File soundQuestionFile, String url,
			Map<String, String> reqHeader) throws Exception {
		String respString = null;
		HttpURLConnection conn = null;
		BufferedInputStream fin = null;
		BufferedOutputStream out = null;
		URL reqUrl;
		try {
			reqUrl = new URL(url);
			conn = (HttpURLConnection) reqUrl.openConnection();
			conn.setConnectTimeout(60000);
			Set<String> key = reqHeader.keySet();
			Iterator it = key.iterator();
			int i=0;
			while (it.hasNext()) {
				String next = (String) it.next();
				conn.setRequestProperty(next, reqHeader.get(next));
			}
			conn.setRequestMethod("POST");
			// conn.setUseCaches(true);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// conn.setChunkedStreamingMode(1024*128);
			out = new BufferedOutputStream(conn.getOutputStream());
			fin = new BufferedInputStream(new FileInputStream(soundQuestionFile));
			byte[] buf = new byte[1024 * 128];
			int len = -1;
			while ((len = fin.read(buf)) != -1) {
				out.write(buf, 0, len);
				out.flush();
			}
			respString = bytesToString(conn.getInputStream());
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (fin != null) {
					fin.close();
					fin = null;
				}
				if (out != null) {
					out = null;
				}
				if (conn != null) {
					conn.disconnect();
					conn = null;
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		return respString;
	}
	private static String bytesToString(InputStream is) throws Exception{
		//将流转成字符串
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int len = 0;
		byte[] buffer = new byte[1024];
		while ((len=is.read(buffer))!=-1) {
			baos.write(buffer, 0, len);
		}
		String result = baos.toString();
		//去除双引号
		result=new Utilstr().removeMarks(result);
		return result;
	}
	
}
